import React, {useEffect, useRef, useState} from "react"
import {observerDashboardPageWrapper} from "../../components/dashboardPages/ObserverDashboardPageWrapper";
import {useLiveQuery} from "dexie-react-hooks";
import {GoodsScratchItem, myDatabase} from "../../database/MyDatabase";
import {Pageable} from "../../utils/Page";
import EditOrderItemRow from "../../components/EditOrderItemRow";
import GoodsTable from "../../components/GoodsTable";
import {getGoodsDetail} from "../../apis/GoodsApi";
import {convertAntdTableToExcel, ExportedColumnProps} from "../../utils/AntdTableUtils";
import {Space} from "antd";
import {DeleteOutlined} from "@ant-design/icons";
import LoadableButton from "../../components/LoadableButton";
import {saveWorkbookTo} from "../../utils/FileSaver";
import {preHandleObjectWithDateTimeParser} from "../../utils/Date";

export interface GoodsScratchPageProps {
    id: number
}


const GoodsScratchDetailPage: React.FC<GoodsScratchPageProps> = ({id}) => {
    const [pageable, setPageable] = useState(new Pageable())

    let list = useLiveQuery(() => myDatabase.goodsScratchItem.where("scratchId").equals(id).sortBy("itemId"), [pageable,id])?.map(item=> {
        return item
    }) ?? [];

    let columnsRef = useRef<ExportedColumnProps<any>[]>();

    const [currentDataSource, setCurrentDataSource] = useState<GoodsScratchItem[]>()
    return (
        <>
            <EditOrderItemRow withAmount={false} onFinish={async values => {
                if (values.goodsId) {
                    let response = await getGoodsDetail(values.goodsId);
                    let data = response.data;
                    await myDatabase.goodsScratchItem.add({...data,createdDateTime:data.createdDateTime?.toJSON(), scratchId: id,lastModifiedDateTime: data.lastModifiedDateTime?.toJSON()})
                }
            }} existedGoodsKeys={list.map(it => ({goodsId:it.id,}))}/>
            <Space style={{margin: "12px 0"}}>
                <LoadableButton type={"primary"} onClick={async () => {
                    await saveWorkbookTo(await convertAntdTableToExcel(columnsRef.current!, currentDataSource ?? list), `草稿单${id}`)
                }}>导出</LoadableButton>
            </Space>


            <GoodsTable localeFilter data={list} localeSort onChange={(_, filters, sorter, extra) => {
                setCurrentDataSource(extra.currentDataSource)
            }} customColumns={columns => {
                columnsRef.current = columns;
                return [
                    ...columns,
                    {
                        title: "操作",
                        ignoreInExcel: true,
                        render(_, record) {
                            return <LoadableButton type={"link"}
                                                   danger
                                                   onClick={async (event) => {
                                                       event.stopPropagation()
                                                       await myDatabase.goodsScratchItem.delete(record.itemId!);
                                                   }}>
                                <DeleteOutlined/>
                                删除
                            </LoadableButton>
                        }
                    }
                ]
            }}/>
        </>
    )
}

export default observerDashboardPageWrapper(GoodsScratchDetailPage, "goodsScratches/{id}", "货品草稿单详情")
